package com.csw.android.ffmpegtest.audio

import android.content.Context
import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import androidx.annotation.Keep
import com.csw.android.ffmpegtest.app.MyApplication

@Keep
class AudioTrackUtil {

    private var audioTrack: AudioTrack? = null
        set(value) {
            if (field != value) {
                field?.release()
                field = value
                field?.play()
            }
        }


    /**
     * 初始化音轨
     *
     * @param sampleRateInHz 采样率
     * @param channels 声道数量
     */
    fun createAudioTrack(sampleRateInHz: Int, channels: Int) {
        val channelConfig =
            if (channels == 2) AudioFormat.CHANNEL_OUT_STEREO else AudioFormat.CHANNEL_OUT_MONO
        val audioManager =
            MyApplication.instance.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        val sessionId = audioManager.generateAudioSessionId()    //音频播放id
        audioTrack = AudioTrack(
            AudioAttributes.Builder()
                .setLegacyStreamType(AudioManager.STREAM_MUSIC)//音乐类型输出
                .build(),
            AudioFormat.Builder()
                .setChannelMask(channelConfig)
                .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
                .setSampleRate(sampleRateInHz)
                .build(),
            AudioTrack.getMinBufferSize(
                sampleRateInHz,
                channelConfig, AudioFormat.ENCODING_PCM_16BIT
            ),
            AudioTrack.MODE_STREAM,
            sessionId
        )
    }

    /**
     * 缓冲播放
     */
    fun playBuffer(buffer: ByteArray, length: Int) {
        audioTrack?.run {
            if (playState == AudioTrack.PLAYSTATE_PLAYING) {
                write(buffer, 0, length)
            }
        }
    }

    /**
     * 销毁音轨播放
     */
    fun destroyAudioTrack() {
        audioTrack = null
    }

}